package com.cantor.common.util;

import com.cantor.common.serializer.ToBeSerializedData;

import java.io.*;

public class JdkUtil {

    public static <T> byte[] serialize(T object) {
        try (
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos)
        ) {
            // 包装一层ToBeSerializedData
            ToBeSerializedData<T> data = new ToBeSerializedData<>(object);
            oos.writeObject(data);
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T deserialize(byte[] bytes, Class<T> clz) {
        try (
                ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bis);
        ) {
            // ToBeSerializedData.getTarget拿到真正数据
            return (T) ((ToBeSerializedData) ois.readObject()).getTarget();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

}
